package cn.qdu.controller;

import cn.qdu.model.User;
import cn.qdu.service.UserService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@WebServlet("/user/uploadAvatar")
public class AvatarUploadServlet extends HttpServlet {
    private UserService userService = new UserService();
    private static final int MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB
    private static final int MAX_REQUEST_SIZE = 10 * 1024 * 1024; // 10MB

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/views/auth/login.jsp");
            return;
        }

        if (!ServletFileUpload.isMultipartContent(request)) {
            request.setAttribute("error", "请选择有效的图片文件");
            request.getRequestDispatcher("/views/user/profile.jsp").forward(request, response);
            return;
        }

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(MAX_FILE_SIZE);
        upload.setSizeMax(MAX_REQUEST_SIZE);

        try {
            List<FileItem> items = upload.parseRequest(request);
            for (FileItem item : items) {
                if (!item.isFormField() && item.getSize() > 0) {
                    // 验证文件类型
                    if (!item.getContentType().startsWith("image/")) {
                        request.setAttribute("error", "只允许上传图片文件");
                        request.getRequestDispatcher("/views/user/profile.jsp").forward(request, response);
                        return;
                    }

                    // 生成唯一文件名
                    String fileName = UUID.randomUUID() + "." + FilenameUtils.getExtension(item.getName());
                    String uploadDir = getServletContext().getRealPath("/uploads");
                    File uploadPath = new File(uploadDir);
                    if (!uploadPath.exists()) {
                        uploadPath.mkdirs();
                    }

                    // 保存文件
                    File storeFile = new File(uploadPath, fileName);
                    item.write(storeFile);

                    // 更新数据库中的头像路径
                    String avatarPath = "uploads/" + fileName;
                    if (userService.updateAvatar(currentUser.getUserId(), avatarPath)) {
                        // 强制刷新session中的用户数据
                        User updatedUser = userService.getUserById(currentUser.getUserId());
                        session.setAttribute("currentUser", updatedUser);

                        // 跳转到首页并添加随机参数避免缓存
                        response.sendRedirect(request.getContextPath() + "/home?refresh=" + System.currentTimeMillis());
                    } else {
                        request.setAttribute("error", "头像更新失败");
                        request.getRequestDispatcher("/views/user/profile.jsp").forward(request, response);
                    }
                    return;
                }
            }

            request.setAttribute("error", "请选择要上传的头像文件");
            request.getRequestDispatcher("/views/user/profile.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "头像上传失败: " + e.getMessage());
            request.getRequestDispatcher("/views/user/profile.jsp").forward(request, response);
        }
    }
}